package com.lzp.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.chatbot20171011.models.ChatResponse;
import com.lzp.wechat.common.utils.RecognizeCharacterUtil;
import com.lzp.wechat.entity.WeiXinParameter;
import com.lzp.wechat.entity.message.*;
import com.lzp.wechat.service.MessageService;
import com.lzp.wechat.common.utils.ChatBootUtil;
import com.lzp.wechat.common.utils.WeChatUtil;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Map;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private WeiXinParameter weiXinParameter;

    @Override
    public String messageHandle(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 处理中文乱码
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            // 解析请求消息
            Map<String, String> requestMap = WeChatUtil.parseXml(request);
            log.info("接收到的消息内容：{}", JSON.toJSONString(requestMap));
            // 回复消息
            /*String responseXml = "<xml><ToUserName><![CDATA[" + requestMap.get("FromUserName") + "]]></ToUserName" +
                    "><FromUserName><![CDATA[" + requestMap.get("ToUserName") + "]]></FromUserName><CreateTime" +
                    ">12345678</CreateTime><MsgType><![CDATA[" + requestMap.get("MsgType") + "]]></MsgType><Content" +
                    "><![CDATA[最喜欢小猪猪了~]]></Content></xml>";*/
            String responseXml = replyMessage(requestMap);
            log.info("回复用户[{}]到的消息内容：{}", requestMap.get("ToUserName"), responseXml);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(responseXml.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息处理异常：{}", e.getMessage());
        }
        return "OK";
    }

    // 处理回复消息
    private String replyMessage(Map<String, String> requestMap) {
        String respMsg = null;
        BaseMessage msg = null;
        String msgType = requestMap.get("MsgType");
        switch (msgType) {
            case "text":
                msg = dealTextMassage(requestMap);
                break;
            case "image":
                msg = dealImageMessage(requestMap);
                break;
            case "voice":
                break;
            case "video":
                break;
            case "shortvideo":
                break;
            case "location":
                break;
            case "link":
                break;
            case "event":
                msg = dealEventMessage(requestMap);
                break;
            default:
                break;
        }
        // 将消息对象转换成xml
        if (StringUtils.isNotBlank(msgType)) {
            respMsg = beanToXml(msg);
        }
        return respMsg;
    }

    /**
     * 将消息对象转换成xml
     *
     * @param msg
     * @return
     */
    private String beanToXml(BaseMessage msg) {
        XStream xStream = new XStream();
        xStream.processAnnotations(new Class[]{TextMessage.class, ImageMessage.class, VoiceMessage.class, VideoMessage.class, MusicMessage.class, NewsMessage.class});
        String xml = xStream.toXML(msg);
        return xml;
    }

    /**
     * 处理文本类型消息内容
     * 1.对接阿里云-云小蜜智能对话机器人，实现对话聊天
     * 2.回复图文消息
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealTextMassage(Map<String, String> requestMap) {
        TextMessage textMessage = null;
        String content = requestMap.get("Content");
        try {
            // 用户输入图文时回复一个图文消息
            if (StringUtils.equals("图文", content)) {
                ArrayList<Article> articles = new ArrayList<>();
                Article article = new Article();
                article.setTitle("吾皇万睡！");
                article.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/lqCDmZcwKKIbTy8Seic0F45np8ZS38H3aHzGJoqSia0nc9t5umyeEhwhXXec7u8TzIRBxZkHliaMCqalYTW89Goaw/0");
                article.setUrl("http://www.baidu.com");
                article.setDescription("这就是吾皇！");
                articles.add(article);
                NewsMessage newsMessage = new NewsMessage(requestMap, articles);
                return newsMessage;
            } else if (StringUtils.equals("登录", content)) {
                String url = weiXinParameter.getAuthorizeUrl();
                url = url.replace("APPID", weiXinParameter.getAppId())
                        .replace("REDIRECT_URI", weiXinParameter.getRedirect_uri())
                        .replace("SCOPE", "snsapi_userinfo");
                log.info("登录地址为：{}", url);
                textMessage = new TextMessage(requestMap, "<a href=\"" + url + "\">点击这里登录</a>");
                return textMessage;
            }
            // 调用智能机器人，获取回复消息内容
            ChatResponse chatResponse = ChatBootUtil.chat(content);
            String respMsg = chatResponse.getBody().getMessages().get(0).getText().getContent();
            textMessage = new TextMessage(requestMap, respMsg);
        } catch (Exception e) {
            log.error("调用阿里云-云小蜜智能对话机器人异常，异常原因：{}", e.getMessage());
            e.printStackTrace();
        }
        return textMessage;
    }

    /**
     * 处理图片类型消息（图片识别）
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealImageMessage(Map<String, String> requestMap) {
        TextMessage textMessage = null;
        String picUrl = requestMap.get("PicUrl");
        String content = "";
        try {
            content = RecognizeCharacterUtil.RecognizeCharacter(picUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("图片识别异常：{}", e.getMessage());
        }
        textMessage = new TextMessage(requestMap, content);
        return textMessage;
    }


    /**
     * 处理Event事件推送
     *
     * @param requestMap
     */
    private BaseMessage dealEventMessage(Map<String, String> requestMap) {
        String event = requestMap.get("Event");
        switch (event) {
            case "CLICK":
                return dealClickEventMessage(requestMap);
            default:
                break;
        }
        return null;
    }

    /**
     * 处理点击事件消息
     *
     * @param requestMap
     */
    private BaseMessage dealClickEventMessage(Map<String, String> requestMap) {
        String eventKey = requestMap.get("EventKey");
        switch (eventKey) {
            case "1":
                return new TextMessage(requestMap, "点击了一级菜单");
            case "31":
                return new TextMessage(requestMap, "点击了第三个一级菜单的第一个子菜单");
            default:
                break;
        }
        return null;
    }

}
